package com.example.my_rabbitmq_high_demo.exchange.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: Direct模式消费者
 * @Author: GaoJian
 * @Date: 2022/7/3 20:32
 */
public class ConsumerByDirect {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1、创建工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");

        //2、获取连接
        Connection connection = factory.newConnection();

        //3、创建channel
        Channel channel = connection.createChannel();

        //4、声明
        //交换机名称
        String exchangeName = "test_direct_exchange";
        //交换机类型
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        //Direct模式RoutingKey必须和生产者保持一致才能消费
        String routingKey = "test.direct";
        //表示声明一个队列，后面几个参数分别为durable、autoDelete、internal、arguments
        //交换机属性：
        //Name : 交换机名称
        //Type : 交换机类型, direct, topic, fanout, headers
        //Durability : 是否需要持久化, true为持久化
        //Auto Delete : 当最后一个绑定到Exchange上的队列删除后, 自动删除该Exchange
        //Internal : 当前Exchange是否用于RabbitMQ内部使用, 默认为False, 这个属性很少会用到
        //Arguments : 扩展参数, 用于扩展AMQP协议制定化使用
        channel.exchangeDeclare(exchangeName, exchangeType, true, false,false, null);
        //声明一个队列, 后面四个参数分别为durable, exclusive, autoDelete, arguments
        //durable : 是否持久化消息
        channel.queueDeclare(queueName, false, false, false, null);
        //建立一个绑定关系
        channel.queueBind(queueName, exchangeName, routingKey);
        //创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数：队列名，autoAck：是否自动确认，consumer
        channel.basicConsume(queueName, true, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("接收到的消息：" + msg);
        }
    }
}
